import { http } from '@/api/service/request';

interface RagResponse<T> {
  code: number;
  message: string;
  data: T;
}

// SSE事件类型定义
export interface SSEEvent {
  type: 'delta' | 'finish' | 'error' | 'status' | 'open' | 'token' | 'complete' | null;
  data: any;
}

// 智谧API响应格式
export interface ZhipuResponse {
  id: string;
  created: number;
  model: string;
  choices: Array<{
    index: number;
    delta: {
      role: string;
      content: string;
    }
  }>;
}

// 流式请求选项
export interface ChatStreamOptions {
  message: string;
  retrievalType?: string; // 检索类型：VECTOR、GRAPH、ENHANCED、PARALLEL、AUTO
  success?: (data: SSEEvent) => void;
  fail?: () => void;
  complete?: (success: boolean, message?: string) => void;
}

/**
 * 流式聊天接口
 * @param options 流式请求选项
 */
export const chatStream = (options: ChatStreamOptions) => {
  const { message, retrievalType = 'AUTO', success, fail, complete } = options;

  // 创建AbortController用于取消请求
  const controller = new AbortController();

  // 构建URL
  const url = `/api/rag/chat/stream/rag?message=${encodeURIComponent(message)}&retrievalType=${retrievalType}`;

  // fetch请求流式接口
  const responsePromise = fetch(url, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
    },
    signal: controller.signal
  }).catch((e) => {
    const msg = e.toString() || '流式接口异常';
    complete?.(false, msg);
    return Promise.reject(e);
  });

  responsePromise
    .then((response) => {
      if (!response?.ok) {
        complete?.(false, response.statusText);
        fail?.();
        throw new Error('Request failed');
      }

      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      if (!reader) throw new Error('No reader available');

      // 存储当前正在处理的事件
      let currentEventType: string | null = null;
      let currentEventData: string = '';
      let buffer: string = '';
      // 记录上一个事件类型，用于处理连续的data行
      let lastEventType: string | null = null;

      async function processText({ done, value }: ReadableStreamReadResult<Uint8Array>): Promise<void> {
        if (done) {
          complete?.(true);
          return Promise.resolve();
        }

        const chunk = decoder.decode(value, { stream: true });
        buffer += chunk;
        
        // 按行分割并处理
        const lines = buffer.split(/\r?\n/);
        buffer = lines.pop() || ''; // 保留可能不完整的最后一行
        
        for (const line of lines) {
          if (line.startsWith('event:')) {
            // 设置新的事件类型
            lastEventType = currentEventType;
            currentEventType = line.substring(6).trim();
            
            // 如果事件类型变化了且有数据，发送之前的事件
            if (lastEventType && lastEventType !== currentEventType && currentEventData) {
              success?.({ type: lastEventType as any, data: currentEventData });
              currentEventData = '';
            }
          } else if (line.startsWith('data:')) {
            const data = line.substring(5).trim();
            
            if (currentEventType === 'token') {
              try {
                // 尝试解析为智谧API格式的JSON
                const jsonData = JSON.parse(data) as ZhipuResponse;
                // 提取content内容
                const content = jsonData.choices?.[0]?.delta?.content || '';
                
                // 发送token事件，数据为content内容
                success?.({ type: 'token', data: content });
              } catch (e) {
                // 如果解析失败，按原来的方式处理
                if (data.includes('\n') || data === '') {
                  if (currentEventData) {
                    // 先发送之前累积的内容
                    success?.({ type: currentEventType as any, data: currentEventData });
                  }
                  // 发送当前内容（包括空行）
                  success?.({ type: currentEventType as any, data: data });
                  currentEventData = ''; // 重置当前数据
                } else {
                  // 不包含换行的普通内容
                  if (currentEventData) {
                    // 如果有累积的内容，发送并重置
                    success?.({ type: currentEventType as any, data: currentEventData });
                  }
                  currentEventData = data;
                }
              }
            } else {
              // 对于其他类型事件，直接使用新数据
              currentEventData = data;
              // 立即发送非token类型的事件
              if (currentEventType) {
                success?.({ type: currentEventType as any, data: currentEventData });
                currentEventData = '';
              }
            }
          } else if (line === '' && currentEventType && currentEventData) {
            // 空行表示事件结束，发送累积的数据
            success?.({ type: currentEventType as any, data: currentEventData });
            currentEventData = '';
          }
        }

        // 继续读取流
        return reader.read().then(processText);
      }

      return reader.read().then(processText);
    })
    .catch((error) => {
      console.error('流式请求出错:', error);
      fail?.();
    });

  // 返回控制器用于取消请求
  return controller;
};

/**
 * 与知识库对话（带来源）
 * @param message 用户消息
 */
export const chatWithSources = (message: string) => {
  return http.post<
    RagResponse<{
      message: string;
      sources: Array<{
        text: string;
        source?: string;
        type?: string;
      }>;
    }>,
    any
  >('/rag/chat/with-sources', { params: { message } });
};

/**
 * 图增强向量检索对话
 * @param message 用户消息
 */
export const enhancedChat = (message: string) => {
  return http.post<
    RagResponse<{
      message: string;
      sources: Array<{
        text: string;
        source?: string;
        type?: string;
      }>;
      retrieval_mode: string;
    }>,
    any
  >('/rag/chat/enhanced', { params: { message } });
};

/**
 * 仅向量检索对话
 * @param message 用户消息
 */
export const vectorChat = (message: string) => {
  return http.post<
    RagResponse<{
      message: string;
      sources: Array<{
        text: string;
        source?: string;
      }>;
      retrieval_mode: string;
    }>,
    any
  >('/rag/chat/vector', { params: { message } });
};

/**
 * 仅图检索对话
 * @param message 用户消息
 */
export const graphChat = (message: string) => {
  return http.post<
    RagResponse<{
      message: string;
      sources: Array<{
        text: string;
        query?: string;
      }>;
      retrieval_mode: string;
    }>,
    any
  >('/rag/chat/graph', { params: { message } });
};

/**
 * 处理文档
 * @param file 文件对象
 */
export const processDocument = (file: File) => {
  const formData = new FormData();
  formData.append('file', file);

  return http.post<
    RagResponse<{
      message: string;
      fileName: string;
    }>,
    any
  >('/rag/document', { data: formData });
};

/**
 * 获取支持的检索类型列表
 */
export const getRetrievalTypes = () => {
  return http.get<
    RagResponse<
      Array<{
        type: string;
        name: string;
        description: string;
      }>
    >,
    any
  >('/rag/retrieval-types');
};
